package com.webapp.stockwatcher.client;

import java.io.IOException;

import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;




import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dev.util.collect.HashMap;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;

import com.google.gwt.json.client.JSONObject;

import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.Maps;
import com.google.gwt.maps.client.control.LargeMapControl;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.webapp.stockwatcher.facebook.Facebook;
import com.webapp.stockwatcher.facebook.FacebookObject;

public class GetFriends implements EntryPoint{
	


	
	/*private VerticalPanel _mainPanel = new VerticalPanel();
	private FlexTable _stocksFlexTable = new FlexTable();
	private HorizontalPanel _addPanel = new HorizontalPanel();
	private TextBox _newSymbolTextBox = new TextBox();
	private Button _addStockButton = new Button("Add");
	private Label _lastUpdatedLabel = new Label();
	private ArrayList<String> stocks = new ArrayList<String>();*/
	private Button _getFriendsOnMap = new Button("Find Friends!");
	private Map<String,String> userLocationMap = new HashMap<String, String>();
	private ThreadPoolExecutor th = null;
	private static final String baseRequestUrl = "http://maps.googleapis.com/maps/api/geocode/json?address=";
	private static final String endRequestUrl = "&sensor=false";
	private static final Integer STATUS_CODE_OK = 200;
	
	@Override
	public void onModuleLoad() {
		
		_getFriendsOnMap.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				//make the call to the thread to execute
				executeFacebookDataRetreival();
				
			}
		});
		
		
		
		
		/*_stocksFlexTable.setText(0, 0, "Symbol");
		_stocksFlexTable.setText(0, 1, "Price");
		_stocksFlexTable.setText(0, 2, "Change");
		_stocksFlexTable.setText(0, 3, "Remove");
		
		_addPanel.add(_newSymbolTextBox);
		_addPanel.add(_addStockButton);
		
		_mainPanel.add(_stocksFlexTable);
		_mainPanel.add(_addPanel);
		_mainPanel.add(_lastUpdatedLabel);
		*/
		RootPanel.get("stockList").add(_getFriendsOnMap);
		
		/*_newSymbolTextBox.setFocus(true);
		
		_addStockButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				
				addStock();
			}
	
		});
		
		_newSymbolTextBox.addKeyPressHandler(new KeyPressHandler() {
			
			@Override
			public void onKeyPress(KeyPressEvent event) {
				if(event.getCharCode() == KeyCodes.KEY_ENTER){
					addStock();
				}
				
				
			}
		});
		
		Timer refreshTimer = new Timer(){

			@Override
			public void run() {
				refreshWatchList();
				
			}
		};
		refreshTimer.scheduleRepeating(REFRESH_INTERVAL);
			*/
		
		
		
	}


	protected void buildUi() {
		// 
		
		
	}


	protected void executeFacebookDataRetreival() {
		
		th = new ThreadPoolExecutor(4, 4, 3000L, TimeUnit.MILLISECONDS, 
				new ArrayBlockingQueue<Runnable>(5));
		final MapWidget map = new MapWidget();
		Maps.loadMapsApi("", "2", false, new Runnable() {
			
			@Override
			public void run() {
				
				map.setSize("100%", "100%");
				map.addControl(new LargeMapControl());
				
			}
		});
		
		runTask(new Runnable() {
			
			@Override
			public void run() {
				Facebook f = new Facebook("126494412964|2.AQAxq4g3Ye__qU_e.3600.1311285600.0-511183593|o5aXU2sdgmlxZ3EVC7uLf7FFsB8");
				FacebookObject me;
				try {
					me = f.api("me", "friends");
					for(int i = 0; i< me.friends.data.length; i++){
						FacebookObject friend = f.api(me.friends.data[i].getId());
						
						if(friend.location != null){
							//System.out.println(i + " : " + friend.getName() + " : " + friend.location.getName());
							userLocationMap.put(friend.getName(), friend.location.getName());
							//add markers to map here
							
							RequestBuilder request = new RequestBuilder(RequestBuilder.GET, baseRequestUrl + friend.location.getName() + endRequestUrl); 
								
							
							try {
								Request response = request.sendRequest(null, new RequestCallback() {
									
									@Override
									public void onResponseReceived(Request request, Response response) {
										
										if(STATUS_CODE_OK == response.getStatusCode()){
											JSONObject json = new JSONObject();
											
											
											
											
										}
									}
									
									@Override
									public void onError(Request request, Throwable exception) {
										
										exception.printStackTrace();
										
									}
								});
							} catch (RequestException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							
						}
						
					}
					System.out.println("The number of friends you have is = " + me.friends.data.length);
				
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				//add markers on the map.
			}
		});
		
	}


	public void runTask(Runnable task){
		th.execute(task);
	}
	
	


	/*protected void refreshWatchList() {
		final double MAX_PRICE = 100.00;
		final double MAX_CHANGE = 0.02;
		
		StockPrice[] prices = new StockPrice[stocks.size()];
		for(int i=0; i < stocks.size(); i++){
			double price = Random.nextDouble() * MAX_PRICE;
			double change = price * MAX_CHANGE * (Random.nextDouble() * 2.0 - 1.0);
			prices[i] = new StockPrice(stocks.get(i), price, change);
		}
		updateTables(prices);
	}


	@SuppressWarnings("deprecation")
	private void updateTables(StockPrice[] prices) {
		for(int i=0; i < prices.length; i++){
			updateTable(prices[i]);
		}
		
		_lastUpdatedLabel.setText("Last Update : " + com.google.gwt.i18n.client.DateTimeFormat.getMediumDateTimeFormat().format(new Date()));
		
	}
	
	

	private void updateTable(StockPrice stockPrice) {
		
		if(!stocks.contains(stockPrice.getSymbol())){
			return;
		}
		
		int row = stocks.indexOf(stockPrice.getSymbol()) + 1;
		
		String priceText = NumberFormat.getFormat("#,##0.00").format(stockPrice.getPrice());
		NumberFormat changeFormat = NumberFormat.getFormat("+#,##0.00;-#,##0.00");
		String changeText = changeFormat.format(stockPrice.getChange());
		String changePercentText = changeFormat.format(stockPrice.getChangePercentage());
		
		_stocksFlexTable.setText(row, 1, priceText);
		_stocksFlexTable.setText(row, 2, changeText + " (" + changePercentText + "%)");
	}


	protected void addStock() {
		final String symbol = _newSymbolTextBox.getText().toUpperCase().trim();
		_newSymbolTextBox.setFocus(true);
		
		if(!symbol.matches("^[0-9A-Z\\.]{1,10}$")){
			Window.alert("'" + symbol + "' is not a valid symbol.");
			_newSymbolTextBox.selectAll();
			return;
		}
		
		_newSymbolTextBox.setText("");
		if(stocks.contains(symbol)){
			return;
		}
		
		int row = _stocksFlexTable.getRowCount();
		stocks.add(symbol);
		_stocksFlexTable.setText(row, 0, symbol);
		
		
		Button removeStockButton = new Button("X");
		removeStockButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				int removeIndex = stocks.indexOf(symbol);
				stocks.remove(removeIndex);
				_stocksFlexTable.removeRow(removeIndex + 1);
				
			}
		});
		_stocksFlexTable.setWidget(row, 3, removeStockButton);
		
		refreshWatchList();
		
		}*/
		
	}
	
